package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.ExpensesDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.Expenses;
import com.huike.pmps.model.entity.Provinces;
import com.huike.pmps.model.entity.Region;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.ExpensesService;
import com.huike.pmps.service.ProvincesService;
import com.huike.pmps.service.RegionService;
import com.huike.pmps.utils.PmpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Slf4j
public class ExpensesServiceImpl implements ExpensesService {
    @Autowired
    ExpensesDao expensesDao;
    @Autowired
    RegionService regionService;
    @Autowired
    ProvincesService provincesService;

    @Override
    public Result insertByImportExpenses(MultipartFile file) {

        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"年份", "月份", "提交人", "标题", "消费事由", "报销金额", "支付金额", "支付日期", "收款信息", "费用类型", "业务类型", "战区", "省区", "备注", "PO单号", "所属财年", "财年支出金额", "产品线成本/费用", "产品线维度"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).getStringCellValue()))
                    return Result.failure("模板标题行已被修改，请勿修改供应商模板标题行");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<Expenses> expensesList = new ArrayList<>();
            XSSFRow row = null;
            Date date = new Date();
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);

                //年份
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 年份为空");
                Integer year = Double.valueOf(row.getCell(0).toString()).intValue();

                //月份
                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 月份 为空");
                Integer month = Double.valueOf(row.getCell(1).toString()).intValue();

                //提交人
                if (row.getCell(2) == null || StringUtils.isBlank(row.getCell(2).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 提交人 为空");
                String submitterName = row.getCell(2).toString();

                //标题
                if (row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 标题 为空");
                String title = row.getCell(3).toString();

                //消费事由
                if (row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 消费事由 为空");
                String reason = row.getCell(3).toString();

                //报销金额
                if (row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  报销金额 为空");
                BigDecimal submitAmount = BigDecimal.valueOf(Double.valueOf(row.getCell(5).toString()));

                //支付金额
                if (row.getCell(6) == null || StringUtils.isBlank(row.getCell(6).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  支付金额 为空");
                BigDecimal paymentAmount = BigDecimal.valueOf(Double.valueOf(row.getCell(6).toString()));

                //支付日期
                if (row.getCell(7) == null || StringUtils.isBlank(row.getCell(7).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  支付日期 为空");

                Date paymentDate = row.getCell(7).getDateCellValue();//row.getCell(7) == null ? null : simpleDateFormat.parse(row.getCell(7).toString());
                Integer weekOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.WEEK_OF_YEAR);
                Integer seasonOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.SEASON);
                Integer monthOfYear = PmpUtil.getDateInfo(paymentDate, GlobalConstants.MONTH);


                //收款信息
                String payeeInfo = row.getCell(8) == null || StringUtils.isBlank(row.getCell(8).toString()) ? null : row.getCell(8).toString();

                //费用类型
                if (row.getCell(9) == null || StringUtils.isBlank(row.getCell(9).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  费用类型 为空");
                String feeType = row.getCell(9).toString();

                //业务类型
                if (row.getCell(10) == null || StringUtils.isBlank(row.getCell(10).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  业务类型 为空");
                String businessType = row.getCell(10).toString();


                //战区 和 省区
                Integer regionId, provinceId = null;
                String regionName, provinceName = null;
                if (row.getCell(11) == null || StringUtils.isBlank(row.getCell(11).toString())) {
                    return Result.success("第" + i + "条数据,战区为空，本次导入全部失败");
                } else {
                    Region region = regionService.selectOneByRegionName(row.getCell(11).toString().substring(0, 2));
                    if (region != null) {
                        regionId = region.getId();
                        regionName = region.getRegion();
                    } else {
                        return Result.success("第" + i + "条数据,战区数据填写有误,请按规则填写");
                    }
                }
                if (row.getCell(12) == null || StringUtils.isBlank(row.getCell(12).toString())) {
                    return Result.success("第" + i + "条数据,省份为空，本次导入全部失败");
                } else {
                    Provinces provinces = provincesService.selectByProvinceName(row.getCell(12).toString().substring(0, 2));
                    if (provinces != null) {
                        provinceId = provinces.getProvinceId();
                        provinceName = provinces.getProvince();
                    } else {
                        return Result.success("第" + i + "条数据,省份数据填写有误,请按规则填写");
                    }
                }

                //备注
                String remark = row.getCell(13) == null || StringUtils.isBlank(row.getCell(13).toString()) ? null : row.getCell(13).toString();

                //PO单号
                String po = row.getCell(14) == null || StringUtils.isBlank(row.getCell(14).toString()) ? null : row.getCell(14).toString();

                //所属财年
                if (row.getCell(15) == null || StringUtils.isBlank(row.getCell(15).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  所属财年 为空");
                Integer financialYear = row.getCell(15).toString().contains("2019") || row.getCell(15).toString().contains("19") ? 2019 :
                        row.getCell(15).toString().contains("2020") || row.getCell(15).toString().contains("20") ? 2020 :
                                row.getCell(15).toString().contains("2021")|| row.getCell(15).toString().contains("21") ? 2021 : 2020;


                // 财年支出金额
                /*if (row.getCell(16) == null || StringUtils.isBlank(row.getCell(16).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  财年支出金额 为空");*/
                BigDecimal fyPaymentAmount = row.getCell(16) == null || StringUtils.isBlank(row.getCell(16).toString()) ? BigDecimal.valueOf(0) : BigDecimal.valueOf(Double.valueOf(row.getCell(16).toString()));


                //产品线成本/费用
               /* if (row.getCell(17) == null || StringUtils.isBlank(row.getCell(17).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据   产品线成本/费用 为空");*/
                String productLineCostName = " 外采成本"; //row.getCell(17).toString();


                //产品线维度
               /* if (row.getCell(18) == null || StringUtils.isBlank(row.getCell(18).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据  产品线维度 为空");*/
                String productLine = row.getCell(18) == null || StringUtils.isBlank(row.getCell(18).toString()) ? null : row.getCell(18).toString();

                Expenses expenses = Expenses.builder().year(year).month(month).submitterName(submitterName).title(title).reason(reason)
                        .submitAmount(submitAmount).paymentAmount(paymentAmount).paymentDate(paymentDate).payeeInfo(payeeInfo)
                        .feeType(feeType).businessType(businessType).remark(remark).regionId(regionId).regionName(regionName)
                        .provinceId(provinceId).provinceName(provinceName).po(po).financialYear(financialYear).fyPaymentAmount(fyPaymentAmount)
                        .productLine(productLine).productLineCostName(productLineCostName)
                        .weekOfYear(weekOfYear).seasonOfYear(seasonOfYear).monthOfYear(monthOfYear).createTime(date)
                        .build();
                expensesList.add(expenses);

            }
            if (expensesList.size() > 0) {
                expensesDao.insertBatchList(expensesList);
                return Result.success("全部导入成功");
            } else {
                return Result.failure("表格中没有数据");
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.failure("导入失败，读取表格数据异常" + e.getMessage());
        }
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, Integer regionId, Integer provinceId, String po, String title, String reason, String feeType, Integer year, Integer month) {

        QueryWrapper<Expenses> queryWrapper = new QueryWrapper<>();
        if (regionId != null)
            queryWrapper.eq("region_id", regionId);
        if (provinceId != null)
            queryWrapper.eq("province_id", provinceId);
        if (StringUtils.isNotBlank(po)) {
            queryWrapper.eq("po", po);
        }
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.eq("title", title);
        }
        if (StringUtils.isNotBlank(reason)) {
            queryWrapper.eq("reason", reason);
        }
        if (StringUtils.isNotBlank(feeType)) {
            queryWrapper.eq("fee_type", feeType);
        }
        if (year != null)
            queryWrapper.eq("year", year);
        if (month != null)
            queryWrapper.eq("month", month);


        Page<Expenses> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<Expenses> pageList = expensesDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }

    }
}
